//
//  SelfFillingMutables.m
//  SolarSeek
//
//  Created by Erick Fejta on 05/02/04.
//  Copyright 2005 Erick Fejta. All rights reserved.
//

#import "SelfFillingMutables.h"


@implementation SelfFillingMutableDictionary
- (id)init {
	if(self = [super init]) {
		_d = [[NSMutableDictionary alloc] init];
	}
	return self;
}

- (id)initWithCapacity:(unsigned)items {
	if(self = [super init]) {
		_d = [[NSMutableDictionary alloc] init];
	}
	return self;
}

- (void)dealloc { 
	[_d release];
	[super dealloc];
}

- (void)setObject:(id)o forKey:(id)k { 
	[self willChangeValueForKey:k];
	[_d setObject:o forKey:k];
	[self didChangeValueForKey:k];
}
- (void)removeObjectForKey:(id)k { 
	[self willChangeValueForKey:k];
	[_d removeObjectForKey:k];
	[self didChangeValueForKey:k];
}

- (unsigned)count { return [_d count];}

- (id)objectForKey:(id)k { 
	NSAssert([self respondsToSelector:@selector(createObjectForNewKey:)],@"Subclasses of SelfFillingMutableDictionary must respond to createObjectForNewKey:");
	
	id o =  [_d objectForKey:k]; 
	if(o==nil) {
		o = [self createObjectForNewKey:k];
		[self setObject:o forKey:k];
	}
	return o;
}

- (NSEnumerator *)keyEnumerator { return [_d keyEnumerator]; }
@end

#pragma mark -

@implementation RandomMutableSet

- (id)init { 
	if(self = [super init]) {
		_s = [[NSMutableSet alloc] init];
	}
	return self;
}

- (id)initWithArray:(NSArray *)a {
	if(self = [self init]) {
		_s = [[NSMutableSet alloc] initWithArray:a];
	}
	return self;
}

- (id)initWithSet:(NSSet *)s {
	if(self = [self init]) {
		_s = [[NSMutableSet alloc] initWithSet:s];
	}
	return self;
}

- (id)initWithCapacity:(unsigned)cap {
	if(self = [self init]) {
		_s = [[NSMutableSet alloc] initWithCapacity:cap];
	}
	return self;
}

- (void)dealloc { 
	[_s release];
	[_e release];
	[super dealloc];
}

- (unsigned)count { return [_s count]; }
- (NSEnumerator *)objectEnumerator { return [_s objectEnumerator]; }
- (void)addObject:(id)object { [_s addObject:object]; }
- (void)removeObject:(id)object { [_e release]; _e = nil; [_s removeObject:object]; }

- (id)anyObject {
	id o = [_e nextObject];
	if(o == nil) {
		[_e release];
		_e = [[[self allObjects] objectEnumerator] retain];
		o = [_e nextObject];
	}
	return o;
}

- (id)member:(id)object {
	return [_s member:object];
}

@end

@implementation SelfFillingMutableSet

- (id)member:(id)object {
	id r = [_s member:object];
	if(r==nil) {
		[self addObject:object];
		r=object;
	}
	return r;
}

@end

